package com.cch.demo.sys.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cch.demo.sys.domain.Dept;
import com.cch.demo.sys.domain.Role;
import com.cch.demo.sys.domain.User;
import com.cch.demo.sys.service.DeptService;
import com.cch.demo.sys.service.RoleService;
import com.cch.demo.sys.service.UserService;
import com.cch.demo.sys.util.*;
import com.cch.demo.sys.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import sun.security.provider.MD5;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 华哥
 * @since 2020-03-06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userServiceImpl;

    @Resource
    private DeptService deptServiceImpl;

    @Resource
    private RoleService roleServiceImpl;


    /**
     * 加载数据表格
     * @param userVo
     * @return
     */
    @RequestMapping("loadAllUser")
    public DataGridView LoadAllUser(UserVo userVo){
        IPage<User> page = new Page<>(userVo.getPage(),userVo.getLimit());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();


        queryWrapper.eq(StringUtils.isNotBlank(userVo.getName()), "loginname", userVo.getName()).or().eq(StringUtils.isNotBlank(userVo.getName()), "name", userVo.getName());
        queryWrapper.like(userVo.getDeptid()!=null,"deptid",userVo.getDeptid());
        queryWrapper.like(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());

        queryWrapper.eq("type", Constast.USER_TYPE_NORMAL);//查询系统用户
        userServiceImpl.page(page,queryWrapper);

        List<User> list = page.getRecords();
        for(User user:list){
            Integer deptid = user.getDeptid();
            //如果dept不为null
            if(deptid!=null) {
                Dept one =deptServiceImpl.getById(deptid);
                user.setDeptname(one.getTitle());
            }
            Integer mgr = user.getMgr();
            //如果mgr不为null
            if(mgr!=null) {
                User one = userServiceImpl.getById(mgr);
                user.setLeadername(one.getName());
            }
        }
        return new DataGridView(page.getTotal(),list);
    }


    @RequestMapping("addUser")
    public ResultObj addUser(UserVo userVo){
        try {
            //设置类型
            userVo.setType(Constast.USER_TYPE_NORMAL);//设置类型
            //设置创建时间
            userVo.setHiredate(new Date());
            //设置盐
            String salt = IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(salt);
            //设置默认密码
            userVo.setPwd(new Md5Hash(Constast.USER_DEFALUT_PASSWORD,salt,2).toString());
            userServiceImpl.save(userVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 删除
     * @param userVo
     * @return
     */
    @RequestMapping("deleteUser")
    public ResultObj deleteUser(Integer id){
        try {
            userServiceImpl.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }


    @RequestMapping("updateUser")
    public ResultObj updateUser(UserVo userVo){
        try {
            userServiceImpl.updateById(userVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 重置密码
     */
    @RequestMapping("resetUserPwd")
    public ResultObj updateUser(Integer id){
        try {
            User user = new User();
            user.setId(id);
            //设置盐
            String salt = IdUtil.simpleUUID().toUpperCase();
            user.setSalt(salt);
            //设置默认密码
            user.setPwd(new Md5Hash(Constast.USER_DEFALUT_PASSWORD,salt,2).toString());

            userServiceImpl.updateById(user);
            return ResultObj.RESET_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.RESET_ERROR;
        }
    }

    /**
     * 初始化排排序码
     * @return
     */
    @RequestMapping("loadUserMaxOrderNum")
    public Map<String,Object> loadUserMaxOrderNum(){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<User> list = userServiceImpl.list(queryWrapper);
        if(list.size()>0){
            map.put("value",list.get(0).getOrdernum()+1);
        }else{
            map.put("value",1);
        }
        return map;
    }

    /**
     * 根据部门ID查询用户
     */

    @RequestMapping("loadUsersByDeptId")
    public DataGridView loadUsersByDeptId(Integer deptid){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(deptid!=null,"deptid",deptid);
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        queryWrapper.eq("type",Constast.USER_TYPE_NORMAL);

        List<User> list = userServiceImpl.list(queryWrapper);
        return new DataGridView(list);
    }

    @RequestMapping("loadNameToPinyin")
    public Map<String,Object> loadNameToPinyin(String name){
        Map<String,Object> map=new HashMap<>();
        if(null!=name) {
            map.put("value", PinyinUtil.ToPinyin(name));
        }else {
            map.put("value", "");
        }

        return map;
    }

    /**
     * 根据用户ID查询一个用户
     * @param id
     * @return
     */
    @RequestMapping("loadUserById")
    public DataGridView loadUserById(Integer id){
        return new DataGridView(userServiceImpl.getById(id));
    }

    /**
     * 根据用户id初始化角色数据表格
     */
    @RequestMapping("initRoleByUserId")
    public DataGridView initRoleByUserId(Integer id){
        //1,查询所有可用的角色
        QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("available", Constast.AVAILABLE_TRUE);
        List<Map<String, Object>> listMaps = roleServiceImpl.listMaps(queryWrapper);

        //2,查询当前用户拥有的角色ID集合
        List<Integer> currentUserRoleIds=roleServiceImpl.queryUserRoleIdsByUid(id);
        for(Map<String, Object> map:listMaps){
            Boolean LAY_CHECKED=false;
            for(Integer rid:currentUserRoleIds){
                if(map.get("id")==rid){
                    LAY_CHECKED=true;
                    break;
                }
            }
            map.put("LAY_CHECKED",LAY_CHECKED);
        }

        return new DataGridView(Long.valueOf(listMaps.size()),listMaps);
    }
}

